'''
Created on Jan 11, 2010

@author: Alex
'''

import pickle
import pygame

try:
	import Tkinter as tk
	import tkFileDialog
except:
	print ("Failed to import Tkinter")

from filemanager import FileManager
from tile import Tile
class FileLoad(FileManager):
	'''
	represents a base grid
	'''


	def __init__(self):
		'''
		Constructor
		'''
		FileManager.__init__(self)
		tk_root = tk.Tk()
		tk_root.withdraw()
		
	def load(self):
		'''
		Checks given filename for supported extensions
		'''
		self.filename = tkFileDialog.askopenfilename(defaultextension='.mpy', filetypes=[('supported', ('*.mpy', '*.png', '*.jpg', '*.bmp')), ('map files', '*.mpy'), ('tilesets', ('*.png', '*.jpg', '*.bmp'))])
		if self.filename.endswith(".mpy"):
			return self.__load_map()
		elif self.filename.endswith(".png") or self.filename.endswith(".jpg") or self.filename.endswith(".bmp"):
			return self.__load_image()
		else:
			print ("Selected file not supported")
		
	def __load_map(self):
		'''
		Loads a made map from a map file ".mpy"
		'''
		boundArray = []
		listArray = []
		if self.connect(self.filename, 'rb') == 0:
			print ("Error while loading file")
			return
		check = pickle.load(self.pickle_open)
		if isinstance(check, int):
			boundArray = pickle.load(self.pickle_open)
			temp = pickle.load(self.pickle_open)
		elif len(check) > 0 and len (check[0]) == 2:
			temp = check
		while 1:
			listArray.append(Tile(temp[0], temp[1], None, temp[2]))
			try:
				temp = pickle.load(self.pickle_open)
			except:
				break
		self.close_connection()
		return boundArray, listArray
		
	
	def __load_image(self):
		'''
		Loads a tile set from an image file ".png", ".jpg", ".bmp"
		'''
		return pygame.image.load(self.filename)